package com.zimmur.service.impl.paynotify;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.zimmur.dao.paynotify.IAlipayNotifyLogDao;
import com.zimmur.model.account.CouponDetail;
import com.zimmur.model.account.PrepaidLog;
import com.zimmur.model.goods.GoodsOrganization;
import com.zimmur.model.order.Order;
import com.zimmur.model.order.OrderDetail;
import com.zimmur.model.wxpay.AlipayNotifyLog;
import com.zimmur.service.account.ICouponService;
import com.zimmur.service.account.IPrepaidLogService;
import com.zimmur.service.goods.IGoodsOrganizationService;
import com.zimmur.service.order.IOrderDetailService;
import com.zimmur.service.order.IOrderService;
import com.zimmur.service.paynotify.IAlipayNotifyLogService;
import com.zimmur.tools.DateUtils;

/**
 * 支付宝支付通知处理服务
 * @author Administrator
 *
 */
@Service("alipayNotifyLogServiceImpl")
public class AlipayNotifyLogServiceImpl implements IAlipayNotifyLogService {
	private static Logger log=LoggerFactory.getLogger(AlipayNotifyLogServiceImpl.class);
	@Resource
	private IAlipayNotifyLogDao alipayNotifyDao;
	@Resource
	private IOrderService orderService;
	@Resource
	private IPrepaidLogService prepaidLogService;
	@Resource
	private IOrderDetailService orderDetailService;
	@Resource
	private IGoodsOrganizationService goodsOrganizationService;
	@Resource
	private ICouponService couponService;
	
	private static Object syncLock = new Object();
	
	@Override
	public boolean addNotifyLog(AlipayNotifyLog model) {
		boolean bRet = false;
		boolean isOrganization=false;
		try{
			//注意：
			//付款完成后，支付宝系统发送该交易状态通知
			//请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
			alipayNotifyDao.insertSelective(model);
			boolean bProcess=true;
			boolean isuserCoupon=false;
			String OutTradeNo = model.getOutTradeNo();
			int couponId=0;
			int payType = 1;//1=订单支付 2=充值支付
			long orderId=0L;
			orderId = Long.parseLong(OutTradeNo);
			Order orderData = orderService.selectByOrderId(orderId);
			if (orderData == null) {
				return bRet;
			}
			if (orderData.getOderStatus().equals("00")) {
				bProcess = false;
			}
			Short isusedCoupon = orderData.getIsusedCoupon();
			if (isusedCoupon != null && isusedCoupon == 1) {
				isuserCoupon = true;
			}
			
			double payJe = model.getTotalFee();
			//WAIT_BUYER_PAY = 交易创建，等待买家付款。
			//TRADE_CLOSED = 在指定时间段内未支付时关闭的交易；在交易完成全额退款成功时关闭的交易
			//TRADE_SUCCESS = 交易成功，且可对该交易做操作，如：多级分润、退款等。
			//TRADE_FINISHED = 	交易成功且结束，即不可再做任何操作
			if(model.getTradeStatus().equals("TRADE_FINISHED") && !bProcess){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
				if(payType==1){					
					orderService.updateOrderStatusByPayNotify(orderId,"alipay",model.getTradeNo(),payJe, "10", "已付款");					
				}
				//注意：
				//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
				//请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
			} else if (model.getTradeStatus().equals("TRADE_SUCCESS") && !bProcess){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序				
				if(payType==1){
					orderService.updateOrderStatusByPayNotify(orderId,"alipay",model.getTradeNo(),payJe, "10", "已付款");
				}
				//更新订单优惠券
				if(isuserCoupon){
					try {
						List<CouponDetail> couponDetails=couponService.selectCouponByOrderId(orderId);
						if (couponDetails!=null) {
							for(CouponDetail couponDetail:couponDetails){
								couponDetail.setCouponState("8");
								couponService.updateCoupon(couponDetail);
								couponService.updateCouponStock(couponDetail.getCouponStockId(), 1, 0, -1);
							}
						}
					} catch (Exception e) {
						log.error(e.getMessage(),e);
					}
				}
				
			}
			bRet = true;
						
		}catch(Exception er){
			log.error(er.getMessage());
			bRet = false;
		}
		
		return bRet;
	}

	@Override
	public AlipayNotifyLog selectByOutTradeNo(String outTradeNo) {
		return alipayNotifyDao.selectByOutTradeNo(outTradeNo);
	}

}
